package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zsk
 * @create 2022-02-17-20:32
 */
@RestController
@Slf4j//记录日志
public class UserController {

    //依赖注入
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /*
    发送验证码
    Request URL: http://localhost:8081/user/sendMsg
    Request Method: POST
     */
    @PostMapping("/user/sendMsg")
    public ResultInfo sendSmsCode(@RequestBody Map<String,String> map){

        //接收参数
        String phone = map.get("phone");

        //生成验证码 todo 临时写死
        //String code = RandomUtil.randomNumbers(6);
        String code = "123";

        //调用阿里云服务把验证吗发送出去
        //smsTemplate.sendSms(phone, code); todo 为了省钱 暂时注释
        log.info("发送的验证码为：" +code);

        //将验证码保存到session数据中，等候检验
//        session.setAttribute("SMS_CODE"+phone,code);
        //使用Redis技术实现(存储5分钟)
        redisTemplate.opsForValue().set("SMS_CODE"+phone,code,5, TimeUnit.MINUTES);

        //返回结果
        return ResultInfo.success(null);
    }

    /*
    注册登录
    Request URL: http://localhost:8081/user/login
    Request Method: POST
     */
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String,String> map){

        //获取账户和密码
        String phone = map.get("phone");
        String code = map.get("code");

        //校验验证码
//        String codeFromSession =(String) session.getAttribute("SMS_CODE"+phone);
//        if (StringUtils.isEmpty(code) ||
//                StringUtils.isEmpty(codeFromSession) ||
//                !StringUtils.equals(code, codeFromSession)) {
//            throw new CustomException("验证码有误");
//        }

        //从Redis中读取验证码跟前端用户做比对
        //强转成String类型
        String codeFromRedis = (String) redisTemplate.opsForValue().get("SMS_CODE" + phone);
        if (StringUtils.isEmpty(code) ||//code为空
            StringUtils.isEmpty(codeFromRedis) || //codeFromRedis为空
             !StringUtils.equals(code,codeFromRedis)){//code与传过来的codeFromRedis不相等
            throw new CustomException("验证码有误！");
        }

        //从数据库中,查询手机号
        User user = userService.findByPhone(phone);

        if (user != null){
            //代表这是一个老用户
        } else {
            //代表这是一个新用户登录
            //保存手机号到用户表中
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }

        //将用户信息保存到session对象中
        session.setAttribute("SESSION_USER",user);

        //返回结果
        return ResultInfo.success(null);
    }

    /*
    展示侧边栏数据
    Request URL: http://localhost:8081/category/list
    Request Method: GET
     */
    @GetMapping("/category/list")
    public ResultInfo list(){
        //调用service层查询数据
        List<Category> categoryList = categoryService.findAll();

        //返回结果
        return ResultInfo.success(categoryList);
    }

    /*
    退出登录
    Request URL: http://localhost:8081/user/logout
    Request Method: POST
     */
    @PostMapping("/user/logout")
    public ResultInfo logout(){
        //删除session里存储的数据
        session.invalidate();
        //返回结果
        return ResultInfo.success(null);
    }


}
